import { Avatar, Empty, List, Space } from 'antd'
import { LikeOutlined, MessageOutlined } from '@ant-design/icons'
import './index.scss'
import {  useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import dayjs from 'dayjs'
import { useDispatch, useSelector } from 'react-redux'
import { fetchCollectInfo } from '@/store/modules/collectStore'
import { getBlogInfoAPI } from '@/api/blog'
import avater from '@/assets/avater.jpeg'

const Article = (props) => {
  const { blogList} = props

  // 分页
  const [params, setParams] = useState({
    page: 1,
    per_page: 2,
    begin_pubdate: null,
    end_pubdate: null
  })
  const pageChange = (page) => {
    // 拿到当前页参数 修改params
    setParams({
      ...params,
      page
    })
}
    // 获取点赞博客信息
    const dispacth = useDispatch()
    const userId = useSelector(state => state.user.userInfo.id)
    const starInfo = useSelector(state => state.collect.collectInfo)

    const [starBlogList, setStarBlogList] = useState([])

    useEffect(() => {
        const getStarInfo = async () => {
            await dispacth(fetchCollectInfo(userId))
        }
        // 获取喜欢博客信息
        const fetchBlogInfo = async () => {
          if (starInfo && starInfo.length) {
            const requestArray = starInfo.map(async (item) => {
            return await getBlogInfoAPI(item.blogId)
            })
            try {
                const results = await Promise.all(requestArray)
                setStarBlogList(results)
            } catch (error) {
                // 错误处理
                console.error(error)
            }
        }           
      }
        if (starBlogList.length === 0) {
            getStarInfo().then(fetchBlogInfo)
        }
    }, [dispacth, userId, starBlogList])

// 去往博客详情
const navigate = useNavigate()
const handleToDetail = (id) => {
  const selectedBlog = blogList.find((item) => item.id === id)
  if (Object.keys(selectedBlog)) {
    if (starInfo && starInfo.length) {
      starInfo.map((item) => {
        if (item.blogId === id) {
            navigate('/detail', { state: { blogId: id, isStar: true, starId: item.id  } })
        }else{
              navigate('/detail', { state: { blogId: id, isStar: false, starInfo} })
            } 
    })
    }else{
          navigate('/detail', { state: { blogId: id, isStar: false, starInfo} })
        } 
  } 
}
  return (
    <div className="article">
      { blogList && blogList.length !== 0 ?
        <List
        itemLayout="vertical"
        size="large"
        pagination={{
          current: params.page,
          pageSize: params.per_page,
          onChange: pageChange,
          total: (blogList && blogList.length) || 0
        }} 
        dataSource={blogList}
        renderItem={(item) => (
          <List.Item
            key={item.id}
            actions={[
              <Space key={`like-${item.id}`}>
                <LikeOutlined />
                {item.likeNum}
              </Space>,
              <Space key={`message-${item.id}`}>
                <MessageOutlined />
              </Space>
            ]}
            onClick={() => handleToDetail(item.id)}
          >
            <List.Item.Meta
              avatar={<Avatar src={avater} />}
              title={item.title}
              description={dayjs(item.createTime).format('YYYY-MM-DD')}
            />
            <div className="content" >
              <span>{item.text.replace(/<img[^>]+>|<br>/g, '')}</span>
            </div>
          </List.Item>
        )}
      />
      : <div>
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      </div> }
    </div>
  )
}

export default Article